package com.hc.config.satoken;


import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.fastjson2.JSONArray;
import com.hc.config.redis.service.RedisService;
import com.hc.domain.redis.RedisKeycof;
import com.hc.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义权限加载接口实现类
 * 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private UserService userService;
    @Resource
    private RedisService redisService;



    /**
     *  返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {

        String userName = loginId.toString();
        String  perKey= RedisKeycof.PERMISSION_PREFIX +userName;
        String permmisionString = redisService.get(perKey);
        List<String> list;
        if(StringUtils.isBlank(permmisionString)){
            list = userService.listPermissionsByUserName(userName);
            redisService.set(perKey,list,RedisKeycof.EXPIRE_TIME);
            return list;
        }
        list = JSONArray.parseArray(permmisionString, String.class);
        return list;
    }


    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
      * @param loginId
     * @param loginType
     * @return
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String userName = loginId.toString();
        String  roleKey= RedisKeycof.ROLE_PREFIX +userName;
        String roleStr = redisService.get(roleKey);
        List<String> list;
        if(StringUtils.isBlank(roleStr)){
            list = userService.listRolesByUserName(userName);
            redisService.set(roleKey,list,RedisKeycof.EXPIRE_TIME);
            return list;
        }
        list = JSONArray.parseArray(roleStr, String.class);
        return list;
    }

}
